﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Data;
using System.Web.UI.WebControls;
using InventoryManagement;
using MII_FIF.Common;

namespace MII_FIF.Layouts.MII_FIF
{
    public partial class FormStorage : LayoutsPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Generic.IsUserInGroup(Configuration.DeviceManagementGroupName))
            {
                ((Label)Header.FindControl("lblHeader")).Text = "Device Management - Form Storage";
                if (!IsPostBack)
                {
                    ViewState["EditMode"] = false;
                    if (Request.QueryString["ID"] != null)
                    {
                        ViewState["ID"] = Request.QueryString["ID"].ToString();
                        ViewState["EditMode"] = true;
                    }
                    Initialize();
                }
            }
            else
            {
                Response.Redirect(Generic.GenLink("/"));
            }
        }
       
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect(Generic.GenLink("/_layouts/MII_FIF/DeviceManagement/ViewStorage.aspx"));
        }       

        void Initialize()
        {
            #region BindDDL
            System_Brand brand = new System_Brand();
            brand.IsDeleted = false;
            DataTable brandColl = brand.SelectByParam();
            Generic.BindDDL(ddlSystemBrand, brandColl, System_Brand_Fields.Title.ToString(), System_Brand_Fields.ID.ToString());
            /*System_Type type = new System_Type();
            type.IsDeleted = false;
            DataTable typeColl = type.SelectByParam();
            Generic.BindDDL(ddlSystemType, typeColl, System_Type_Fields.Title.ToString(), System_Type_Fields.ID.ToString());*/
            Location location = new Location();
            location.IsDeleted = false;
            DataTable dtLocation = location.SelectByParam();
            Generic.BindDDL(ddlLocation, dtLocation, Location_Fields.Lokasi.ToString(), Location_Fields.ID.ToString());
            Rack_Number rackNumber = new Rack_Number();
            rackNumber.IsDeleted = false;
            DataTable dtRackNumber = rackNumber.SelectByParam();
            Generic.BindDDL(ddlRackNumber, dtRackNumber, Rack_Number_Fields.Title.ToString(), Rack_Number_Fields.ID.ToString());
            #endregion

            if (Request.QueryString["ID"] != null)
            {
                Guid ID = Guid.Empty;
                if (Guid.TryParse(Request.QueryString["ID"], out ID))
                {
                    Inventory_Storage invStorage = new Inventory_Storage();    
                    invStorage.ID = ID;
                    invStorage.Select();
                    lblInventoryBy.Text = invStorage.InventoryBy;
                    ddlRackNumber.SelectedValue = invStorage.ID_RackNumber.ToString();
                    txtLabelName.Text = invStorage.LabelName;
                    ddlLocation.SelectedValue = invStorage.ID_DataCabang.ToString();
                    rblSystemClass.Items.IndexOf(rblSystemClass.Items.FindByValue(invStorage.SystemClass));
                    ddlStartFrom.SelectedValue = invStorage.StartFrom;
                    ddlSystemBrand.SelectedValue = invStorage.ID_SysBrand.ToString();
                    ddlSystemBrand_SelectedIndexChanged(this, EventArgs.Empty);
                    ddlSystemType.SelectedValue = invStorage.ID_SysType.ToString();
                    txtPathNumber.Text = invStorage.PathNumber;
                    txtSerialNumber.Text = invStorage.SerialNumber;
                    txtHostName.Text = invStorage.HostName;
                    txtIPStorage.Text = invStorage.IP;
                    txtHarddiskUnit.Text = invStorage.HDD.ToString();
                    txtHarddiskGB.Text = invStorage.HDDCapacity.ToString();
                    rblPhysical.SelectedValue = invStorage.HW_Physical.ToString();
                    rblPowerSupply.SelectedValue = invStorage.HW_Supply.ToString();
                    rblFAN.SelectedValue = invStorage.HW_FAN.ToString();
                    rblHarddisk.SelectedValue = invStorage.HW_HDD.ToString();
                    txtNotes.Text = invStorage.Notes;
                    ViewState["Link"] = invStorage.URLAttachment;

                    string filename = Generic.GetFileNameFromUrl(invStorage.URLAttachment);
                    lblFileName.Text = filename;
                    btnDownload.Visible = !string.IsNullOrEmpty(filename);
                    lblFileName.Visible = !string.IsNullOrEmpty(filename);
                    FUAttachment.Visible = false;
                }
            }
            else
            {
                lblInventoryBy.Text = SPContext.Current.Web.CurrentUser.Name;
                btnDownload.Visible = false;
                lblFileName.Visible = false;
                FUAttachment.Visible = true;
            }
        }

        bool validasi()
        {
            bool check = true;
            lblerror.Text = string.Empty;
            if (!(bool)ViewState["EditMode"])
            {
                /*
                if (!FUAttachment.HasFile)
                {
                    lblerror.Text += "Please upload attachment. <br />"; check = false;
                }
                else */
                if (Generic.checkUploadedFileName(FUAttachment.FileName))
                {
                    lblerror.Text += "Uploaded file name cannot contains # % & * : < > ? /  { | } <br />"; check = false;
                }
            }
            return check;
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (validasi())
            {
                Inventory_Storage invStorage = new Inventory_Storage();
                invStorage.InventoryBy = lblInventoryBy.Text;
                invStorage.ID_RackNumber = StringUtil.ToGuid(ddlRackNumber.SelectedValue);
                invStorage.LabelName = txtLabelName.Text;
                invStorage.ID_DataCabang = StringUtil.ToGuid(ddlLocation.SelectedValue);
                invStorage.SystemClass = rblSystemClass.SelectedValue;
                invStorage.StartFrom = ddlStartFrom.SelectedValue;
                invStorage.ID_SysBrand = StringUtil.ToGuid(ddlSystemBrand.SelectedValue);
                invStorage.ID_SysType = StringUtil.ToGuid(ddlSystemType.SelectedValue);
                invStorage.PathNumber = txtPathNumber.Text;
                invStorage.SerialNumber = txtSerialNumber.Text;
                invStorage.HostName = txtHostName.Text;
                invStorage.IP = txtIPStorage.Text;
                invStorage.HDD = StringUtil.ToInt32(txtHarddiskUnit.Text);
                invStorage.HDDCapacity = StringUtil.ToInt32(txtHarddiskGB.Text);
                invStorage.HW_Physical = StringUtil.ToBoolean(rblPhysical.SelectedValue);
                invStorage.HW_Supply = StringUtil.ToBoolean(rblPowerSupply.SelectedValue);
                invStorage.HW_FAN = StringUtil.ToBoolean(rblFAN.SelectedValue);
                invStorage.HW_HDD = StringUtil.ToBoolean(rblHarddisk.SelectedValue);
                invStorage.Notes = txtNotes.Text;
                invStorage.InventoryDate = DateTime.Now;
                invStorage.IsDeleted = false;

                if (Request.QueryString["ID"] != null)
                {
                    Guid ID = Guid.Empty;
                    if (Guid.TryParse(Request.QueryString["ID"], out ID))
                    {
                        invStorage.URLAttachment = ViewState["Link"] as string;
                        invStorage.ID = ID;
                        invStorage.Update();
                    }
                }
                else
                {
                    invStorage.URLAttachment = Generic.UploadFile(FUAttachment);
                    invStorage.ID = Guid.NewGuid();
                    invStorage.Insert();
                }
                Response.Redirect(Generic.GenLink("/_layouts/MII_FIF/DeviceManagement/ViewStorage.aspx"));
            }
        }

        protected override void OnPreRender(EventArgs e)
        {

            string script =
                           "function download() {" +
                           "var link ='" + ViewState["Link"] + "';" +
                           "var retvalue = window.open('" + Generic.GenLink("/_layouts/MII_FIF/Download.aspx") + "?links=' + link"
                         + ", '', 'width=1000,height=1000');}";

            Page.ClientScript.RegisterClientScriptBlock(typeof(System.Web.UI.Page), "opendownload", script, true);
        }

        protected void ddlSystemBrand_SelectedIndexChanged(object sender, EventArgs e)
        {
            UpdateSystemType();
        }

        void UpdateSystemType()
        {
            if (!ddlSystemBrand.SelectedValue.Equals("-1"))
            {
                System_Type type = new System_Type();
                type.ID_SystemBrand = StringUtil.ToGuid(ddlSystemBrand.SelectedValue);
                DataTable datatable = type.SelectByParam();
                Generic.BindDDL(ddlSystemType, datatable, System_Type_Fields.Title.ToString(), System_Type_Fields.ID.ToString());
                ddlSystemBrand.Focus();
            }
        }
    }
}
